using System;

namespace SerialPortLibrary
{
    /// <summary>
    /// CRC校验算法
    /// </summary>
    /// <remarks>无需实例化,可以直接使用,如果CRC算法不同,请重写</remarks>
    public class CRC
    {
        /// <summary>
        /// CRC校验数据
        /// </summary>
        public struct CRCData
        {
            public byte CRCHigh;
            public byte CRCLow;
        }
        public static CRCData CRCCaculate(byte[] Data)
        {
            CRCData CRCV = new CRCData();
            long TempVal = 0xFFFF;
            for (int i = 0; i <= (Data.Length - 1); i++)
            {
                TempVal = TempVal ^ Data[i];
                for (int j = 1; j <= 8; j++)
                {
                    long YWval = System.Convert.ToInt64(TempVal / 2);
                    int LSB = (int)(TempVal % 2);
                    if (LSB == 1)
                    {
                        YWval = YWval ^ 0xA001;
                    }
                    TempVal = YWval;
                }
            }
            double CRCValue = TempVal % 65536;
            byte[] list = BitConverter.GetBytes(Convert.ToUInt16(CRCValue));

            CRCV.CRCLow = list[0]; //'先低位
            CRCV.CRCHigh = list[1]; //'后高位

            return CRCV;
        }
    }
}
